package com.RequestGongWuShu;

import java.io.File;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * attention 注意上传可能要修改的地方，在业务上才能正常进行 施工升降机对接测试 注：方法上的注释打√的方法为对接测试环境已通过
 *
 * @author YS
 * @date 2020/12/04 16:58
 */
@Slf4j
public class vehicle {

    private String api_key = "93f608b414e14eb58363c7c3a6e4219d";
    private String api_version = "1.0";
    private String engCode = "GDSYEQ-010-2019";// 工程编号
    private String projectCode = "XM20170281";// 项目编号
    private String baseUlr = "http://szwb.sz.gov.cn:2018/openapi";// 请求地址

    boolean DEBUG = true;

    /**
     * 2021.3.7新增 上传车道闸基本信息 测试完成√√
     */
    public String addBasicInfo(JSONObject param, JSONObject body) {
        log.info("上传车道闸基本信息给工务署平台..");
        String url = baseUlr + "/vehicle/addBasicInfo";

        String jsonBody = JSONObject.toJSONString(body);// body的json字符串

        String timestamp = param.getString("timestamp");// 封装原方法参数
        String api_key = param.getString("api_key");
        String projectCode = param.getString("project_code");
        String engCode = param.getString("eng_code");
        String api_version = param.getString("api_version");
        param.put("body", body);

        String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, jsonBody);

        param.put("signature", signature);

        log.info("请求头参数：" + param.toJSONString());
        log.info("请求体参数：" + jsonBody);
        String info = HttpUtil.post(url, param.toJSONString());
        log.info(info);

        return info;
    }

    /**
     * 2021.3.7新增 上报车辆心跳道闸维持测试完成√√
     */
    public String heartbeat(JSONObject param, JSONObject body) {
        log.info("--------------------------------------");
        log.info("上传车道闸心跳包给工务署平台..");
        String url = baseUlr + "/vehicle/heartbeat";

        String jsonBody = JSONObject.toJSONString(body);// body的json字符串

        String timestamp = param.getString("timestamp");// 封装原方法参数
        String api_key = param.getString("api_key");
        String projectCode = param.getString("project_code");
        String engCode = param.getString("eng_code");
        String api_version = param.getString("api_version");

        String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, jsonBody);

        param.put("signature", signature);
        log.info("请求参数：" + param.toJSONString());
        String info = HttpUtil.post(url, param.toJSONString());
        return parseResult(info, param, url);
        // log.info(info);
    }

    public String parseResult(String resultString, JSONObject param, String url) {

        // 可进行封装工务署返回信息
        JSONObject resultObject = JSONObject.parseObject(resultString);
        String message = null;
        String serverTimestamp = "";
        try {
            message = resultObject.getString("message");
            serverTimestamp = resultObject.getString("serverTimestamp");
        } catch (Exception e) {
            log.error("获取到不正常的信息，返回信息：" + resultString);
            log.error("请求信息 ：" + param.toJSONString());
        }
        if (resultObject.getInteger("code") != 0 || !message.equals("成功")) {
            if (DEBUG)
                log.info("请求参数：" + param.toJSONString());
            if (DEBUG)
                log.info("请求地址：" + url);
            if (DEBUG)
                log.info("返回信息：" + resultString);

            log.warn("（返回信息:信息）" + message);
            log.warn("（返回信息:时间）" + serverTimestamp);
            log.warn("(pinyivehicle_detailed.GwsProjectCode)工务署项目号：" + param.getString("project_code"));
            log.info("--------------------------------------");
            log.info("");
            log.info("");
        } else {
            if (DEBUG)
                log.info("请求参数：" + param.toJSONString());
            if (DEBUG)
                log.info("请求地址：" + url);
            if (DEBUG)
                log.info("返回信息：" + resultString);
            log.info("（返回信息:信息）" + message);
            log.info("（返回信息:时间）" + serverTimestamp);
            log.info("--------------------------------------");
            log.info("");
            log.info("");
        }
        return message;
    }

    /**
     * 2.2.1车辆进出场数据 √ array
     */

    public JSONObject uploadData(JSONObject param, JSONObject body) {
        log.info("上传车辆进出场数据给工务署平台..");
        String url = baseUlr + "/vehicle/uploadData";

        List<JSONObject> bodyList = new ArrayList<>();// 可以传入多个body
        bodyList.add(body);
        param.put("body", bodyList);// body

        String jsonBody = JSONObject.toJSONString(bodyList);// body的json字符串

        log.info("body" + jsonBody);

        String timestamp = param.getString("timestamp");// 封装原方法参数
        String api_key = param.getString("api_key");
        String projectCode = param.getString("project_code");
        String engCode = param.getString("eng_code");
        String api_version = param.getString("api_version");

        String signature = getSignature(api_key, api_version, engCode, projectCode, timestamp, jsonBody);
        param.put("signature", signature);

        log.info("参数：" + param);
        String info = HttpUtil.post(url, param.toJSONString());

        return JSONObject.parseObject(info);

        // return parseResult(info, param, url);
    }

    /**
     * 硬件通用上传图片√
     */
    public String uploadImage(String photoUrl) {
        log.info("上传圖片数据给工务署平台..");
        HashMap<String, Object> paramMap = new HashMap<>();
        String url = "http://szwb.sz.gov.cn:2018/uploadfile-openpai/uploadImage";
        // 文件
        File file = new File(photoUrl);
        // log.info("file:"+file.getAbsolutePath());
        paramMap.put("file", file);
        paramMap.put("api_key", api_key);
        log.info("请求参数：" + url + "paramMap：" + paramMap);
        String result = HttpUtil.post(url, paramMap);
        log.info("上传图片结果：" + result);// 返回文件的id
        // resultData":"ffbe6ac3b17f5a457cbd1a7abfe2ff1e"
        // 解析失败则请求失败或者没有其他异常，抛空
        String gwsPhotoUrl = "";
        try {
            gwsPhotoUrl = JSONObject.parseObject(result).getString("resultData");
        } catch (Exception e) {
            return null;
        }
        return gwsPhotoUrl;
    }

    /**
     * 获取签名
     *
     * @param: [apiKey,
     * apiVersion, engCode, projectCode, timestamp, body]
     * @return: java.lang.String
     */
    public static String getSignature(String apiKey, String apiVersion, String engCode, String projectCode,
                                      String timestamp, String body) {
        String str4MD5 = String.format("api_key%sapi_version%sbody%seng_code=%sproject_code=%stimestamp%s", apiKey,
                apiVersion, body.isEmpty() ? "{}" : body, engCode, projectCode, timestamp);
        return getMD5Code(str4MD5);
    }

    public static String getMD5Code(String strObj) {
        String resultString = null;
        try {
            resultString = new String(strObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            Charset charset = Charset.forName("UTF-8");
            resultString = byteToString(md.digest(strObj.getBytes(charset)));
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return resultString;
    }

    // 转换字节数组为16进制字串
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }

    // 全局数组
    private final static String[] strDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D",
            "E", "F"};

    {
        log.info("param：" + toString());
    }

    @Override
    public String toString() {
        return "vehicle [api_key=" + api_key + ", api_version=" + api_version + ", engCode=" + engCode
                + ", projectCode=" + projectCode + ", baseUlr=" + baseUlr + "]";
    }

    public String getApi_key() {
        return api_key;
    }

    public void setApi_key(String api_key) {
        this.api_key = api_key;
    }

    public String getApi_version() {
        return api_version;
    }

    public void setApi_version(String api_version) {
        this.api_version = api_version;
    }

    public String getEngCode() {
        return engCode;
    }

    public void setEngCode(String engCode) {
        this.engCode = engCode;
    }

    public String getProjectCode() {
        return projectCode;
    }

    public void setProjectCode(String projectCode) {
        this.projectCode = projectCode;
    }

    public String getBaseUlr() {
        return baseUlr;
    }

    public void setBaseUlr(String baseUlr) {
        this.baseUlr = baseUlr;
    }

}
